package com.yunfangdata.service.impl;

import com.yunfangdata.domain.Employee;
import com.yunfangdata.domain.Role;
import com.yunfangdata.mapper.EmployeeMapper;
import com.yunfangdata.query.QueryObject;
import com.yunfangdata.service.IEmployeeService;
import com.yunfangdata.util.PageResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper mapper;

    public void save(Employee entity) {
        mapper.insert(entity);
    }

    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    public void update(Employee entity) {

        //删除旧关系
        mapper.deleteEmpAndRoleRelation(entity.getId());
        //保存新关系
        List<Role> roles = entity.getRoles();

        for (Role role : roles) {
            mapper.saveEmpAndRoleRelation(entity.getId(),role.getId());
        }

        mapper.updateByPrimaryKey(entity);
    }

    public Employee get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<Employee> list() {
        return mapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int total = mapper.queryForCount(qo);

        if (total == 0){
            return new PageResult();
        }
        List<Employee> rows = mapper.queryForList(qo);
        return new PageResult(total,rows);
    }

    public List<Employee> queryEmployeeByRoleManager() {
        return mapper.queryEmployeeByRoleManager();
    }


    public void changeState(Long id) {
        mapper.changeState(id);
    }


    public Employee queryCurrentUserByEmpUsernameAndPassword(String un, String psw) {
        return mapper.queryCurrentUserByEmpUsernameAndPassword(un,psw);
    }

    public Employee queryCurrentUserByEmpUsername(String uname) {
        return mapper.queryCurrentUserByEmpUsername(uname);
    }

    public void changePassword(String username, String password,String newPassword) {
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        password = new Md5Hash(password,employee.getUsername(),3).toString();
        newPassword = new Md5Hash(newPassword,employee.getUsername(),3).toString();
        int i = mapper.changePassword(username, password, newPassword);
        if(i!=1){
            throw new RuntimeException("亲 ! 原密码输入有误 , 修改失败 ");
        }
    }

    public Employee queryPortraitByUsername(String username) {
        return mapper.queryPortraitByUsername(username);
    }
}
